<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'list';
$keytypes=get_keyword_types();
$backtypes=get_back_types('id','title');
if($_RQ['op']=='list'){
	$params=array();
	$params['uniacid']=$_SESSION['uniacid'];
	if(!empty($_RQ['title'])){
		$search_type=intval($_RQ['search_type']);
		if($search_type){
			$sql='SELECT `back_id` FROM ' . tablename('core_back_keyword') . ' WHERE `uniacid`=:uniacid and ((`type`=1 and `keyword`=:keyword) or (`type`=2 and `keyword` like :keywordlike) or (`type`=3 and :keyword REGEXP `keyword`))';
			$params1=array(':uniacid'=>$_SESSION['uniacid'],':keyword'=>$_RQ['title'],':keywordlike'=>'%'.$_RQ['title'].'%');
			$back_ids=pdo_fetchall($sql,$params1);
			$params['id']=array();
			$params['id'][]=0;
			foreach($back_ids as $back_id){
				$params['id'][]=$back_id['back_id'];
			}
			$return['params']['search_type']=1;
		}else{
			$params['title like']='%'.trim($_RQ['title']).'%';
			
		}
		$return['params']['title']=$_RQ['title'];
	}
	$orderby=array();
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array('id','title','backtype','status','createtime');
	$list=pdo_getslice('core_back',$params,array($pindex,$psize),$total,$fields,'','id desc');
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['backtypes']=$backtypes;
	$htmls=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'list','title'=>'回复规则列表'),
		),
		'list'=>array('data'=>'list','tip'=>'【温馨提示】
		</br>1、非认证公众号？非认证公众号处理，只处理文本消息、图文消息、音乐消息，通过被动回复接口回复消息，一次只能回复一条；
		</br>2、认证公众号，通过客服接口回复消息，可同时回复多条消息；
		</br>3、<red>关键词不触发</red>？检查公众号设置正常（微信公众号后台--开发--基本配置--服务器配置(已启用)--提交配置），如果上面配置好了，还是无法触发，请检查：开发者密码(AppSecret)是否正确（因为是隐藏的，每次获取都要重置，重置后很容易忘记对应修改！）
		','list'=>array(
			array('name'=>'title','title'=>'规则名称','type'=>'string','set'=>'set'),
			array('name'=>'backtype','title'=>'回复类型','type'=>'radio','options'=>'backtypes'),
			array('name'=>'status','title'=>'是否开启','type'=>'switch','set'=>'set'),
			array('name'=>'createtime','title'=>'创建时间','type'=>'time'),
		)),
		'search_one'=>array('name'=>'title','select_name'=>'search_type','options'=>'search_types','is_radio'=>true),
	);
	$return['search_types']=array(
		0=>'根据规则名称搜索',
		1=>'根据关键词匹配',
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op']=='edit'){
	$return=array('keytypes'=>$keytypes,'backtypes'=>$backtypes);
	$id=intval($_RQ['id']);
	if($id){
		$item=pdo_get('core_back',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		if($item){
			$item['keywords']=pdo_getall('core_back_keyword',array('back_id'=>$id),array('id','type','keyword'));
			if($item['backtype']==2){
				$item['content1']=json_decode($item['content'],true);
				$item['content']=array('content'=>'');
			}else{
				$item['content']=json_decode($item['content'],true);
				$item['content1']=array();
			}
		}
	}else{
		$item=array('content'=>array('content'=>''),'content1'=>array());
	}
	$return['item']=$item;
	$htmls=array(
		'type'=>'edit',
		'post'=>'post',
		'tabs'=>array(
			'0'=>array('op'=>'list','title'=>'关键字回复列表'),
			'1'=>array('op'=>'edit','title'=>'关键字回复编辑'),
		),
		'edits'=>array(
			array(
				//'title'=>'回复关键字',
				'list'=>array(
					array(
						'type'=>'array',
						//'title'=>'列表',
						'name'=>'keywords',
						'add_tip'=>'添加一个关键词',
						'list'=>array(
							array('type'=>'string','name'=>'keyword','title'=>'关键词内容'),
							array('type'=>'radio','name'=>'type','title'=>'关键词类型','options'=>'keytypes'),
						),'details'=>array(
							array('type'=>'radio','name'=>'type','title'=>'关键词类型','options'=>'keytypes','help'=>'精确匹配：当粉丝输入的内容和本回复规则的关键词一致时触发回复。</br>模糊匹配：当粉丝输入的内容包含本回复规则的关键词时触发回复。</br>正则匹配：使用MySQL的匹配引擎，请使用MySQL的正则语法。</br>正则匹配示例: ^微信匹配以“微信”开头的语句；</br>微信$匹配以“微信”结尾的语句；</br>^微信$匹配等同“微信”的语句；</br>微信匹配包含“微信”的语句；</br>[0-9.-]匹配所有的数字，句号和减号；</br>^[a-zA-Z_]$所有的字母和下划线；</br>^[[:alpha:]]{3}$所有的3个字母的单词；</br>^a{4}$aaaa；^a{2,4}$aa，aaa或aaaa；^a{2,}$匹配多于两个a的字符串。'),
							array('type'=>'string','name'=>'keyword','title'=>'关键词内容','help'=>''),
						)
					),
				)
			),
			array(
				'title'=>'回复内容设置',
				'list'=>array(
			
					array('type'=>'string','title'=>'回复规则名称','name'=>'title','help'=>'' ),
					array('type'=>'radio','title'=>'回复类型','name'=>'backtype','options'=>'backtypes','help'=>'' ),
					array('type'=>'string','title'=>'排序','name'=>'paixu','help'=>'' ),
					array('type'=>'switch','title'=>'是否开启','name'=>'status'),
					array('type'=>'text_wx','title'=>'回复内容','tovalue'=>'pagedata.item.content','name'=>'content','show'=>array('backtype',1,'pagedata.item.backtype')),
					array('type'=>'tip','show'=>array('backtype'=>2),'title'=>'（注意，接微信官方通知，自2018年10月12日起，被动消息回复接口和客服消息接口回复图文消息只允许一篇图文，因此此处只能设置一篇图文。）'),
					array(
						'type'=>'array',
						'title'=>'图文内容设置',
						'name'=>'content1',
						'show'=>array('backtype'=>2),
						'add_tip'=>'添加一条图文',
						'list'=>array(
							array('type'=>'image','name'=>'picurl','title'=>'封面'),
							array('type'=>'string','name'=>'title','title'=>'标题'),
						),'details'=>array(
							array('type'=>'string','name'=>'title','title'=>'标题'),
							array('type'=>'image','name'=>'picurl','title'=>'封面图片'),
							array('type'=>'text','name'=>'description','title'=>'描述'),
							array('type'=>'link','name'=>'url','title'=>'图文链接'),
						)
					),
					array('type'=>'image','title'=>'图片','tovalue'=>'pagedata.item.content','name'=>'url','show'=>array('backtype',3,'pagedata.item.backtype')),
					array('type'=>'audio','title'=>'设置音频','tovalue'=>'pagedata.item.content','name'=>'url','show'=>array('backtype',4,'pagedata.item.backtype')),
					array('type'=>'video','title'=>'设置视频','tovalue'=>'pagedata.item.content','name'=>'url','show'=>array('backtype',5,'pagedata.item.backtype')),
					array('type'=>'audio','title'=>'设置音乐','tovalue'=>'pagedata.item.content','name'=>'musicurl','show'=>array('backtype',6,'pagedata.item.backtype')),
					array('type'=>'string','title'=>'音乐标题','tovalue'=>'pagedata.item.content','name'=>'title','show'=>array('backtype',6,'pagedata.item.backtype')),
					array('type'=>'image','title'=>'封面图片','tovalue'=>'pagedata.item.content','name'=>'picurl','show'=>array('backtype',6,'pagedata.item.backtype')),
					array('type'=>'string','title'=>'音乐描述','tovalue'=>'pagedata.item.content','name'=>'description','show'=>array('backtype',6,'pagedata.item.backtype')),
					array('type'=>'string','title'=>'视频标题','tovalue'=>'pagedata.item.content','name'=>'title','show'=>array('backtype',5,'pagedata.item.backtype')),
					array('type'=>'image','title'=>'封面图片','tovalue'=>'pagedata.item.content','name'=>'picurl','show'=>array('backtype',5,'pagedata.item.backtype')),
					array('type'=>'string','title'=>'视频描述','tovalue'=>'pagedata.item.content','name'=>'description','show'=>array('backtype',5,'pagedata.item.backtype')),
				),
			)
		)
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op']=='post'){
	$postdata=get_postdata();
	//print_r($postdata);exit;
	$data=array(
		'title'=>trim($postdata['title']),
		'backtype'=>intval($postdata['backtype']),
		'paixu'=>intval($postdata['paixu']),
		'status'=>intval($postdata['status']),
	);
	//图文回复区分处理
	if($data['backtype']==2){
		if(count($postdata['content1'])>1){
			exi('接微信官方通知，自2018年10月12日起，被动消息回复接口和客服消息接口回复图文消息只允许一篇图文，因此此处只能设置一篇图文。请调整设置！','error');
		}
		$data['content']=ijson_encode($postdata['content1']);
	}else{
		$data['content']=ijson_encode($postdata['content']);
	}
	$id=intval($postdata['id']);
	if($id){
		pdo_update('core_back',$data,array('id'=>$id));
	}else{
		$data['createtime']=TIMESTAMP;
		$data['uniacid']=$_SESSION['uniacid'];
		pdo_insert('core_back',$data);
		$id=pdo_insertid();
	}
	if($postdata['keywords']){
		$ids=array();
		$old=pdo_getall('core_back_keyword',array('back_id'=>$id),array('id'),'id');
		$old=array_keys($old);
		foreach($postdata['keywords'] as &$keyword){
			$data=array(
				'type'=>intval($keyword['type']),
				'keyword'=>$keyword['keyword'],
			);
			if($keyword['id']){
				$ids[]=$keyword['id'];
				pdo_update('core_back_keyword',$data,array('id'=>$keyword['id'],'uniacid'=>$_SESSION['uniacid']));
			}else{
				$data['uniacid']=$_SESSION['uniacid'];
				$data['back_id']=$id;
				pdo_insert('core_back_keyword',$data);
			}
		}
		//删除多余关键词
		foreach($old as $row){
			if(!in_array($row,$ids)){
				pdo_delete('core_back_keyword',array('id'=>$row));
			}
		}
	}
	exi('操作成功！','','list');
	
}
if($_RQ['op']=='set'){
	$id=intval($_RQ['id']);
	if(!$id){
		exi('参数错误！','error');
	}
	$update=array();
	$post=get_postdata();
	if(isset($post['status'])){
		$update['status']=intval($post['status']);
	}
	if($post['title']){
		$update['title']=trim($post['title']);
	}
	if($update){
		pdo_update('core_back',$update,array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
	}
	exi('操作成功！');
}
if($_RQ['op']=='del'){
	$id=intval($_RQ['id']);
	if($id){
		pdo_delete('core_back',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
	}
	$del=trim($_RQ['del'],';');
	if($del){
		$del=explode(';',$del);
		foreach($del as $id){
			$id=intval($id);
			if($id){
				pdo_delete('core_back',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
			}
		}
	}
	exi('删除成功！');
}
if($_RQ['op']=='get_back'){
	$params=array();
	$params['uniacid']=$_SESSION['uniacid'];
	if(!empty($_RQ['title'])){
		$search_type=intval($_RQ['search_type']);
		if($search_type){
			$sql='SELECT `back_id` FROM ' . tablename('core_back_keyword') . ' WHERE `uniacid`=:uniacid and ((`type`=1 and `keyword`=:keyword) or (`type`=2 and `keyword` like :keywordlike) or (`type`=3 and :keyword REGEXP `keyword`))';
			$params1=array(':uniacid'=>$_SESSION['uniacid'],':keyword'=>$_RQ['title'],':keywordlike'=>'%'.$_RQ['title'].'%');
			$back_ids=pdo_fetchall($sql,$params1);
			$params['id']=array();
			$params['id'][]=0;
			foreach($back_ids as $back_id){
				$params['id'][]=$back_id['back_id'];
			}
			$return['params']['search_type']=1;
		}else{
			$params['title like']='%'.trim($_RQ['title']).'%';
			
		}
		$return['params']['title']=$_RQ['title'];
	}
	$orderby=array();
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$total='';
	$fields=array('id','title','backtype','status','createtime');
	$list=pdo_getslice('core_back',$params,array($pindex,$psize),$total,$fields,'','id desc');
	if($list){
		foreach($list as &$item){
			//整理返回数据
			if($_RQ['op']=='many'){
				$item['res']=array('mid'=>$item['id'],'title'=>$item['title']);
			}else{
				$item['res']=$item['id'];
			}
		}
	}
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$return['backtypes']=$backtypes;
	$return['htmls']=array(
		'type'=>'list',
		'list'=>array('data'=>'list','del_one'=>false,'delall'=>false,'edit'=>false,'list'=>array(
		    array('name'=>'id','title'=>'规则id','type'=>'string'),
			array('name'=>'title','title'=>'规则名称','type'=>'string','set'=>'set'),
			array('name'=>'backtype','title'=>'回复类型','type'=>'radio','options'=>'backtypes'),
		),'action'=>array(
			array('type'=>'modal_result','name'=>'res','title_field'=>'nickname','title'=>'选取'),
		)),
		'search_one'=>array('name'=>'title','select_name'=>'search_type','options'=>'search_types','is_radio'=>true),
	);
	$return['search_types']=array(
		0=>'根据规则名称搜索',
		1=>'根据关键词匹配',
	);
	exi($return);
}